package com.note.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 全局CORS跨域配置
 * 支持WebMVC和WebFlux两种模式
 */
@Configuration
@ConditionalOnProperty(name = "cors.enabled", havingValue = "true", matchIfMissing = true)
public class GlobalCorsConfig {

    /**
     * 创建CORS配置
     */
    private CorsConfiguration corsConfig() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有来源
        config.addAllowedOriginPattern("*");
        // 允许所有头
        config.addAllowedHeader("*");
        // 允许所有方法
        config.addAllowedMethod("*");
        // 允许携带Cookie
        config.setAllowCredentials(true);
        // 暴露所有头信息
        config.addExposedHeader("*");
        // 预检请求的有效期，单位秒
        config.setMaxAge(3600L);
        return config;
    }

    /**
     * WebMVC模式的CORS配置（应用服务和中间件服务）
     */
    @Bean
    @ConditionalOnProperty(name = "spring.main.web-application-type", havingValue = "servlet", matchIfMissing = true)
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .exposedHeaders("*")
                        .maxAge(3600);
            }
        };
    }

    /**
     * 备用方案：通过过滤器配置CORS（应用服务和中间件服务）
     */
    @Bean
    @ConditionalOnProperty(name = "spring.main.web-application-type", havingValue = "servlet", matchIfMissing = true)
    public CorsFilter corsFilter() {
        org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new org.springframework.web.cors.UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    /**
     * WebFlux模式的CORS配置（网关服务）
     */
    @Bean
    @ConditionalOnProperty(name = "spring.main.web-application-type", havingValue = "reactive")
    public CorsWebFilter reactiveFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsWebFilter(source);
    }
} 